<template>
  <div class="users">
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="formData" :rules="formDataRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="formData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="formData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editData" :rules="editFormDataRules" ref="editRuleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="editData.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editData.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editData.email"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区 -->
    <el-card>
      <!-- 头部添加与搜索 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input clearable @clear="getUser" v-model="params.query" placeholder="请输入内容">
            <el-button @click="getUser" slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible=true">添加</el-button>
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="users" border>
        <el-table-column prop="username" label="用户名"/>
        <el-table-column prop="mobile" label="电话"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="changeUserState(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="role_name" label="角色"/>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" @click="editUser(scope.row.id)" icon="el-icon-edit" size="mini"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" @click="deleteUser(scope.row.id)"  icon="el-icon-delete" size="mini"></el-button>
            <!-- 分配角色 -->
            <el-tooltip content="分配角色"  effect="dark" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页条 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="params.pagenum"
      :page-sizes="[1, 2, 5, 10]" :page-size="params.pagesize" layout="total, sizes, prev, pager, next, jumper" :total="total">
    </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 手机号验证
    var checkMobile = (rule, value, callback) => {
      const regMobile = /^1[3|4|5|7|8][0-9]{9}$/
      if (regMobile.test(value)) return callback()
      callback(new Error('手机号格式不正确'))
    }
    // 邮箱验证
    var checkEmail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
      if (regEmail.test(value)) return callback()
      callback(new Error('邮箱式不正确'))
    }
    return {
      users: [],
      params: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      dialogVisible: false,
      editDialogVisible: false,
      // 表单提交数据
      formData: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 修改用户数据
      editData: {
        id: 0,
        username: '',
        role_id: 0,
        mobile: '',
        email: ''
      },
      // 添加表单验证
      formDataRules: {
        username: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' }
        ],
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
      },
      // 编辑表单验证
      editFormDataRules: {
        mobile: [
          { validator: checkMobile, trigger: 'blur' }
        ],
        email: [
          { validator: checkEmail, trigger: 'blur' }
        ],
      },
    }
  },
  created() {
    this.getUser()
  },
  methods: {
    // 获取用户列表
    async getUser() {
      const { data, meta } = await this.$http.get('users', {
        params: this.params,
      })
      if (meta.status !== 200) return this.$message.error('获取用户列表失败')
      this.users = data.users
      this.total = data.total
      this.params.pagenum = data.pagenum
    },
    handleSizeChange(val) {
      this.params.pagesize = val
      this.getUser()
    },
    handleCurrentChange(val) {
      this.params.pagenum = val
      this.getUser()
    },
    // 修改用户状态
    async changeUserState(userInfo) {
      const { id } = userInfo
      const { meta } = await this.$http.put(`users/${id}/state/${userInfo.mg_state}`)
      if (meta.status === 200) return this.$message.success('修改状态成功')
      this.$message.error('修改状态失败')
      userInfo.mg_state = !userInfo.mg_state
    },
    // 清空添加表单
    addDialogClosed() {
      const { ruleForm } = this.$refs
      ruleForm.resetFields()
    },
    // 添加用户
    addUser() {
      const { ruleForm } = this.$refs
      ruleForm.validate(async valid => {
        if (!valid) return
        const { meta } = await this.$http.post('users',this.formData)
        if (meta.status !== 201) return this.$message.error('添加用户失败')
        this.dialogVisible = false
        this.$message.success('添加用户成功')
        this.getUser()
      })
    },
    // 编辑用户信息
    async editUser(id) {
      this.editDialogVisible = true
      const { meta, data } = await this.$http.get('users/' + id)
      if (meta.status !== 200) return this.$message.error('获取用户信息失败')
      this.editData = data
    },
    // 修改用户信息
    updateUser() {
      const { editRuleForm } = this.$refs
      editRuleForm.validate(async valid => {
        if (!valid) return
        const { id, mobile, email } = this.editData
        const { meta } = await this.$http.put('users/' + id, { mobile, email })
        if (meta.status !== 200) return this.$message.error('修改用户信息失败')
        this.$message.success('修改用户信息成功')
        this.editDialogVisible = false
        this.getUser()
      })
    },
    // 删除用户信息
    async deleteUser(id) {
      const isSure = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (isSure === 'cancel') return
      const { meta } = await this.$http.delete('users/' + id)
      if (meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getUser()
    }
  },
}
</script>

<style lang="less" scoped>

</style>>

